package library.common.view.recyclerview;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Created by qiang.hou on 2019/1/17.
 * @version 1.0
 */
public abstract class CommonRvAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<T> dataSource;

    public CommonRvAdapter(List<T> data) {
        this.dataSource = data;
        if (this.dataSource == null) {
            this.dataSource = new ArrayList<>();
        }
    }

    @NonNull
    @Override
    @SuppressWarnings("unchecked")
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        AdapterItemView item = createItemView(viewType);
        return new CommonViewHolder(parent.getContext(), parent, item);
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof CommonViewHolder) {
            ((CommonViewHolder) holder).bindData(dataSource.get(position), position);
        }
    }

    @Override
    public int getItemCount() {
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        return getItemType(dataSource.get(position));
    }

    /**
     * 创建 adapter 的ItemView
     *
     * @param viewType 需要创建的ItemView的viewType，由getItemType(T item)获取
     * @return 返回这个 viewType 对应的 AdapterItemView
     */
    protected abstract AdapterItemView<T> createItemView(int viewType);

    /**
     * 定义ItemView的viewType
     *
     * @param item T
     * @return int
     */
    protected abstract int getItemType(T item);

    /**
     * common ViewHolder
     *
     * @param <D>
     */
    private class CommonViewHolder<D> extends RecyclerView.ViewHolder {
        private AdapterItemView<D> adapterItemView;

        CommonViewHolder(Context context, ViewGroup parent, AdapterItemView<D> adapterItemView) {
            super(LayoutInflater.from(context).inflate(adapterItemView.getLayoutResId(), parent, false));
            this.adapterItemView = adapterItemView;
            this.adapterItemView.initViews(itemView);
        }

        void bindData(D data, int position) {
            this.adapterItemView.bindData(data, position);
        }
    }

    /**
     * 能被 CommonRvAdapter识别的一个 ItemView
     *
     * @param <T>
     */
    protected interface AdapterItemView<T> {

        int getLayoutResId();

        void initViews(View view);

        void bindData(T data, int position);
    }
}
